package com.yitianyigexiangfa.coap.cbor.cborjava;

import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import com.yitianyigexiangfa.coap.cbor.util.ConvertUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * @author Bill Lau
 * @date 2017-12-22
 */
public class CborJavaMapDemo {

    /*
     *  {"id":"ID123456id", "key":"KEY123456key"}
     */

    public static void main(String[] args) throws CborException {
        // ================== 编码 ==================
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        new CborEncoder(byteArrayOutputStream).encode(
                new CborBuilder()
                        .addMap()
                        .put("id", "ID123456id")
                        .put("key", "KEY123456key")
                        .end()
                        .build()
        );
        byte[] encodeResultAry = byteArrayOutputStream.toByteArray();
        String convertResult = ConvertUtil.bytesToHex(encodeResultAry);
        System.out.println("Encode result : " + convertResult);

        // ================== 解码 ==================
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encodeResultAry);
        List<DataItem> dataItems = new CborDecoder(byteArrayInputStream).decode();
        for (DataItem dataItem: dataItems) {
            System.out.println(dataItem.toString());
        }

    }

}
